﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using EveMarketsDAO;
using EveMarketsDAO.MiseAjourBase;

namespace EveMarkets.Views
{
    /// <summary>
    /// Logique d'interaction pour UpdateMarket.xaml
    /// </summary>
    public partial class UpdateMarket : Page
    {
    	private readonly BackgroundWorker _bgwUpdate; 

        public UpdateMarket()
        {
            InitializeComponent();
			_bgwUpdate = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
			InitializeBackgroundWorker();
        	
        	// Chargement du nombre de ligne dans la table Temporaire.
        	lblNbreLigneTemp.Content = ContexteDAO.FonctionMarkets.NombreLigneTempMarket();
        	lblDateLastUpdate.Content = ContexteDAO.DerniereDateUpdate().ToString();
        }

		private void InitializeBackgroundWorker()
		{
			_bgwUpdate.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
			_bgwUpdate.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
			_bgwUpdate.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
		}

		/// <summary>
		/// Permet de supprimer toutes les lignes dans la table temporaire.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnDeleteTemp_Click(object sender, RoutedEventArgs e)
		{
			lblSuppression.Content = ContexteDAO.ContexteDonnees.DeleteTemp().ToString("N0") + " ligne(s) supprimées.";
		}

		/// <summary>
		/// Permet de mettre à jour la base de donnée.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnLaunch_Click(object sender, RoutedEventArgs e)
		{
			#region Traitement du Parcourir.
			// Si aucun chemin n'est choisi, je remonte une erreur, et je sors.
			if (String.IsNullOrEmpty(txtBoxParcours.Text))
			{
				imgErreurParcourir.Visibility = Visibility.Visible;
				return;
			}

			// Si chemin est bien choisi, je met l'image en Hidden si elle est visible.
			if (imgErreurParcourir.Visibility == Visibility.Visible)
				imgErreurParcourir.Visibility = Visibility.Hidden; 
			#endregion

			// Affichage de la progressBar
			progressBarLaunch.Visibility = Visibility.Visible;
			btnLaunch.IsEnabled = false;
			btnParcours.IsEnabled = false;

			Tuple<string,DateTime> info = new Tuple<string, DateTime>(txtBoxParcours.Text,Convert.ToDateTime(lblDateLastUpdate.Content));
			_bgwUpdate.RunWorkerAsync(info);
		}

		/// <summary>
		/// Permet à l'utilisateur de choisir le répertoire ou sauvegarder les fichiers.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnParcours_Click(object sender, RoutedEventArgs e)
		{
			FolderBrowserDialog repertoire = new FolderBrowserDialog();
			repertoire.ShowNewFolderButton = true;
			repertoire.ShowDialog();

			txtBoxParcours.Text = repertoire.SelectedPath;
			repertoire.Dispose();
		}


		#region Events BackgroundWorker

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			// Get the BackgroundWorker that raised this event.
			BackgroundWorker worker = sender as BackgroundWorker;

			Tuple<string, DateTime> info = (Tuple<string, DateTime>)e.Argument;

			// NOTE : Constructeur dans le cas ou le Market se met bien a jour.
//			MiseAJourMarkets update = new MiseAJourMarkets(TimeZoneInfo.ConvertTimeToUtc(DateTime.Now), info.Item1,info.Item2 );
			MiseAJourMarkets update = new MiseAJourMarkets(TimeZoneInfo.ConvertTimeToUtc(DateTime.Now), info.Item1);

			if (update.ListDesDatesDl.Count > 0)
				//lblLaunch.Content = update.UpdateTheBaseMarket().ToString("N0") + @" ligne(s) mise à jour.";
				e.Result = update.UpdateLaBaseMarket(worker).ToString("N0") + @" line(s) updated.";
			else
				e.Result = @"No updates available";
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			btnLaunch.IsEnabled = true;
			btnParcours.IsEnabled = true;

			// First, handle the case where an exception was thrown.
			if (e.Error != null)
			{
				txtBoxInfo.AppendText(e.Error.Message);
				txtBoxInfo.AppendText(Environment.NewLine);
			}
			else if (e.Cancelled)
			{
				// Next, handle the case where the user canceled 
				// the operation.
				// Note that due to a race condition in 
				// the DoWork event handler, the Cancelled
				// flag may not have been set, even though
				// CancelAsync was called.
				txtBoxParcours.Text = "Action Canceled";
			}
			else
			{
				// Finally, handle the case where the operation 
				// succeeded.
				txtBoxInfo.AppendText(e.Result.ToString());
				txtBoxInfo.AppendText(Environment.NewLine);
			}

			// Mise à jour de la date (pour l'affichage.
			lblDateLastUpdate.Content = ContexteDAO.DerniereDateUpdate().ToString();
		}

		/// <summary>
		/// Met à jour la progress Bar
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			this.progressBarLaunch.Value = e.ProgressPercentage;
			this.txtBoxInfo.AppendText(e.UserState.ToString());
			this.txtBoxInfo.ScrollToVerticalOffset(Double.MaxValue);
			this.txtBoxInfo.AppendText(Environment.NewLine);
			this.txtBoxInfo.ScrollToVerticalOffset(Double.MaxValue);
		} 

		#endregion
    }
}
